<script setup>
import { useResize } from '@/utils/index.js'
import breaks from '@bytemd/plugin-breaks'
import frontmatter from '@bytemd/plugin-frontmatter' // 解析前题
import gemoji from '@bytemd/plugin-gemoji'
import gfm from '@bytemd/plugin-gfm'
import highlight from '@bytemd/plugin-highlight' // 代码高亮
import mediumZoom from '@bytemd/plugin-medium-zoom' // 缩放图片
import { Viewer } from '@bytemd/vue-next'
import zhHans from 'bytemd/locales/zh_Hans.json'
// 掘金同款样式
import 'bytemd/dist/index.css'
import 'juejin-markdown-themes/dist/juejin.min.css'

const props = defineProps({
  content: {
    type: String,
    required: true,
  },
  maxLine: {
    type: Number,
    default: 2,
  },
})

// 插件
const plugins = ref([
  gfm(),
  gemoji(),
  highlight(),
  frontmatter(),
  mediumZoom(),
  breaks(),
])

const viewerRef = ref(null)
const showExpand = ref(false)
const isExpanded = ref(false)
let resizeObserver = null

function checkOverflow() {
  if (!viewerRef.value?.$el)
    return

  const el = viewerRef.value.$el
  const lineHeight = Number.parseInt(getComputedStyle(el).lineHeight) || 24
  const maxHeight = lineHeight * props.maxLine
  const isOverflowing = el.scrollHeight - 1 > maxHeight

  // 只有确实超过maxLine行时才显示展开按钮
  showExpand.value = isOverflowing

  // 如果内容不超过maxLine行，确保不处于展开状态
  if (!isOverflowing) {
    isExpanded.value = false
  }
}

function toggleExpand() {
  isExpanded.value = !isExpanded.value
}

onMounted(() => {
  nextTick(() => {
    if (viewerRef.value?.$el) {
      resizeObserver = useResize(viewerRef.value.$el, checkOverflow)
      // 初始检查
      checkOverflow()
    }
  })
})

onUnmounted(() => {
  if (resizeObserver) {
    resizeObserver.disconnect()
  }
})
</script>

<template>
  <div class="relative">
    <Viewer
      ref="viewerRef"
      :locale="zhHans"
      :value="content"
      :plugins="plugins"
      class="markdown-body"
      :class="[!isExpanded && showExpand ? `line-clamp-${maxLine}` : '']"
    />
    <span
      v-if="showExpand"
      class="cursor-pointer color-primary us"
      @click="toggleExpand"
    >
      {{ isExpanded ? "收起" : "展开" }}
    </span>
  </div>
</template>

<style scoped>
.line-clamp-2 {
  overflow: hidden;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  line-clamp: 2;
}
.line-clamp-5 {
  overflow: hidden;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 5;
  line-clamp: 5;
}
/* 使用 :deep() 确保能穿透到子组件中的 .markdown-body */
:deep(.markdown-body) {
  font-size: 14px;
  overflow: hidden;
}

/* 如果需要选择第一个/最后一个子元素 */
:deep(.markdown-body > :first-child) {
  margin-top: 0;
}

:deep(.markdown-body > :last-child) {
  margin-bottom: 0;
}
</style>
